﻿//-----------------------------------------------------------------------
// <copyright file="AsAnAdministratorIShouldBeAbleChangeAccessRightsAndBeAbleToCheckTheseChangesInTheDashboard.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Utility.Tests.UI.Web.Behaviour.Tenant{    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web.Controllers;
    using AbstractSaaSTemplate.UI.Web.Helpers;
    using AbstractSaaSTemplate.UI.Web.Models.Security;
    using AbstractSaaSTemplate.UI.Web.Models.User;
    using AbstractSaaSTemplate.Utility.Tests.UI.Utilities;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// @14077247
    /// Como Administrador de Distribuidor, de Tenant ou de Conta, eu devo ter
    /// acesso à uma função que me permita visualizar todas as funções controladas
    /// do meu nível de acesso e configurar quais as permissões de acesso existem
    /// para aquele nível de acesso, com caixas de checagem que me permitam
    /// reconfigurar as permissões de acesso que tenho para cada uma destas funções.
    /// </summary>
    [TestClass]
    public class TestFor0014077247
    {
        #region Properties

        /// <summary>
        /// Gets or sets the User controller which will be used in tests.
        /// </summary>
        private UserController UserController { get; set; }
        
        /// <summary>
        /// Gets or sets the Security controller which will be used in tests.
        /// </summary>
        private SecurityController SecurityController { get; set; }

        /// <summary>
        /// Gets or sets the Dashboard controller which will be used in tests.
        /// </summary>
        private DashboardController DashboardController { get; set; }

        #endregion

        #region Setup

        /// <summary>
        /// This method initializes controllers and dependencies for run tests.
        /// </summary>
        [TestInitialize]
        public void Setup()
        {
            TestFor0013453151.EnsureInstallationIsComplete();
            
            var factory = new ApplicationFactory();

            this.UserController = factory.CreateControllerFor<UserController>();
            this.SecurityController = factory.CreateControllerFor<SecurityController>();
            this.DashboardController = factory.CreateControllerFor<DashboardController>();
        }

        #endregion

        /// <summary>
        /// @14077247
        /// Como Administrador de Distribuidor, de Tenant ou de Conta, eu devo ter
        /// acesso à uma função que me permita visualizar todas as funções controladas
        /// do meu nível de acesso e configurar quais as permissões de acesso existem
        /// para aquele nível de acesso, com caixas de checagem que me permitam
        /// reconfigurar as permissões de acesso que tenho para cada uma destas funções.
        /// Passos da Mímica --------------------------------------------------
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// 2.  Executa o teste de remoção de permissão.
        ///     Deve assegurar:
        ///     2.1) Que a função de controle de permissões de acesso está acessível.
        /// 3. Teste de Remoção de Permissões
        ///     3.1) Que é possível remover a permissão de acesso à duas funções do sistema.
        /// 4. Teste de Inclusão de Permissão
        ///     4.1) Que é possível adicionar a permissão de acesso à 1 função do sistema.
        /// 5. Executa o teste de visibilidade de funções
        ///     5.1) Que somente as funções para as quais o administrador do tenant tem acesso estão disponíveis
        /// </summary>
        [TestMethod]
        public void AsAnAdministratorIShouldBeAbleChangeAccessRightsAndBeAbleToCheckTheseChangesInTheDashboard()
        {
            /* =========================================================
             * EXECUÇÃO DA MÍMICA
             * =========================================================
             * Os procedimentos executados à seguir são uma mímica dos
             * procedimentos executados pelos usuários no uso real do sistema.
             * ========================================================= */

            // 1)
            this.LogOnAndAssertActiveUser();

            // 2)
            this.AssertThatTheAccessRightsControlFeatureIsAccessible();

            // 3)
            this.AssertThatWeCanRemoveAccessToFeatures();

            // 4)
            var roleFeatures = this.AssertThatWeCanGrantAccessToFeatures();
            
            // 5)
            this.AssertThatItOnlyFeaturesWithAccessRightsAreVisible(roleFeatures);
        }

        /// <summary>
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// </summary>
        private void LogOnAndAssertActiveUser()
        {
            var distributorAdmin = this.UserController.RepositoryForMembership.GetUsersByRole(
                AccessLevels.Distributor,
                AccessRoles.Administrator).FirstOrDefault();

            this.UserController.MockForTesting("LogOn", HttpVerbs.Post);
            this.UserController.LogOn(
                new LogOnForm()
                {
                    Login = distributorAdmin.Credentials.Login,
                    Password = distributorAdmin.Credentials.RetrievePassword()
                },
                string.Empty);

            var activeUser = this.UserController.ServiceForMembership.ActiveUser;
            Assert.IsNotNull(activeUser);
        }
        
        /// <summary>
        /// 2.  Executa o teste de acessibilidade da função de gerenciamento de permissões.
        ///     Deve assegurar:
        ///     2.1) Que a função de controle de permissões de acesso está acessível.
        /// </summary>
        private void AssertThatTheAccessRightsControlFeatureIsAccessible()
        {
            // 2.1) Que a função de controle de permissões de acesso está acessível.
            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Get);
            var resultForGet = this.SecurityController.ManageRolesAccess();
            Assert.IsInstanceOfType(resultForGet, typeof(ViewResult));

            var actionViewForGet = resultForGet as ViewResult;
            var modelForGet = actionViewForGet.Model;
            Assert.IsInstanceOfType(modelForGet, typeof(ManageRolesAccessForm));

            var typedModelForGet = modelForGet as ManageRolesAccessForm;
            Assert.IsNotNull(typedModelForGet);
        }

        /// <summary>
        /// 3. Teste de Remoção de Permissões
        ///     3.1) Que é possível remover a permissão de acesso à duas funções do sistema.
        /// </summary>
        private void AssertThatWeCanRemoveAccessToFeatures()
        {
            // we load the current access rights
            // and we lock the features that we will remove
            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Get);
            var resultForGet = this.SecurityController.ManageRolesAccess();
            var actionViewForGet = resultForGet as ViewResult;
            var modelForGet = actionViewForGet.Model as ManageRolesAccessForm;
            Assert.IsTrue(modelForGet.RolesAndFeatures.Count() > 2);

            // we remove 2 features from the associantions retrieved
            var forms = new FormCollection();
            var roleFeatures = modelForGet.RolesAndFeatures.ToArray();
            var maxFeatures = roleFeatures.Count() - 2;
            for (var i = 0; i < maxFeatures; i++) 
            {
                var item = roleFeatures[i];
                string fieldName = string.Concat(
                    item.Role.ToString(),
                    "-",
                    item.Feature.ToString());

                forms.Add(fieldName, "on");
            }

            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Post);
            var resultForPost = this.SecurityController.ManageRolesAccess(forms);
            Assert.IsInstanceOfType(resultForPost, typeof(RedirectToRouteResult));

            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Get);
            resultForGet = this.SecurityController.ManageRolesAccess();
            actionViewForGet = resultForGet as ViewResult;
            modelForGet = actionViewForGet.Model as ManageRolesAccessForm;
            Assert.AreEqual<int>(maxFeatures, modelForGet.RolesAndFeatures.Count());
        }

        /// <summary>
        /// 4. Teste de Inclusão de Permissão
        ///     4.1) Que é possível adicionar a permissão de acesso à 1 função do sistema.
        /// </summary>
        /// <returns>Returns the associations between roles and features which have been setup to the application.</returns>
        private IEnumerable<RoleFeature> AssertThatWeCanGrantAccessToFeatures()
        {
            // we load the current access rights
            // and we lock the features that we will remove
            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Get);
            var resultForGet = this.SecurityController.ManageRolesAccess();
            var actionViewForGet = resultForGet as ViewResult;
            var modelForGet = actionViewForGet.Model as ManageRolesAccessForm;

            // we find one feature for which the active user has no access
            // so that we can add this feature to the list
            var roleOfUser = modelForGet.RolesAndFeatures.FirstOrDefault().Role;
            var featureToInclude = modelForGet.Features
                .Where(d =>
                    d != ControlledFeatures.None &&
                    !modelForGet.RolesAndFeatures.Select(e => e.Feature).Contains(d))
                .FirstOrDefault();

            // we prepare the for to post the new selection of features.
            var forms = new FormCollection();

            // we create the fieldName of the new feature to create
            var newFieldName = string.Concat(roleOfUser, "-", featureToInclude);
            forms.Add(newFieldName, "on");

            // we add all existing features to the form to be posted.
            foreach (var roleFeature in modelForGet.RolesAndFeatures)
            {
                var fieldName = string.Concat(roleFeature.Role, "-", roleFeature.Feature);
                forms.Add(fieldName, "on");
            }
            
            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Post);
            var resultForPost = this.SecurityController.ManageRolesAccess(forms);
            Assert.IsInstanceOfType(resultForPost, typeof(RedirectToRouteResult));

            this.SecurityController.ModelState.Clear();
            this.SecurityController.MockForTesting("ManageRolesAccess", HttpVerbs.Get);
            resultForGet = this.SecurityController.ManageRolesAccess();
            actionViewForGet = resultForGet as ViewResult;
            modelForGet = actionViewForGet.Model as ManageRolesAccessForm;
            Assert.AreEqual<int>(forms.Count, modelForGet.RolesAndFeatures.Count());

            return modelForGet.RolesAndFeatures;
        }
        
        /// <summary>
        /// 5. Executa o teste de visibilidade de funções
        ///     5.1) Que somente as funções para as quais o administrador do tenant tem acesso estão disponíveis
        /// </summary>
        /// <param name="roleFeatures">The associations between roles and features.</param>
        private void AssertThatItOnlyFeaturesWithAccessRightsAreVisible(IEnumerable<RoleFeature> roleFeatures)
        {
            // now we test if the features available are the same as
            // the acess rights defined previously.
            this.DashboardController.ModelState.Clear();
            this.DashboardController.MockForTesting("Index", HttpVerbs.Get);

            var resultForGet = this.DashboardController.Index();
            Assert.IsInstanceOfType(resultForGet, typeof(ViewResult));

            var viewResultForGet = resultForGet as ViewResult;
            var modelForGet = viewResultForGet.Model;
            Assert.IsInstanceOfType(modelForGet, typeof(IEnumerable<ControlledFeatureInfo>));

            var listOfControlledFeaturesFromModel = modelForGet as IEnumerable<ControlledFeatureInfo>;
            Assert.IsNotNull(listOfControlledFeaturesFromModel);

            var roleFeaturesToConsider = roleFeatures
                .Where(d => d.Feature != ControlledFeatures.Dashboard)
                .ToArray();

            Assert.AreEqual<int>(
                roleFeaturesToConsider.Count(),
                listOfControlledFeaturesFromModel.Count());
        }
    }
}


